#include "KinectInteraction.h"
#include "Server.h"
#include "pthread.h"
#include <opencv/highgui.h>
#include <opencv/cv.h>
#include <iostream>
#include <fstream>


KinectInteraction *kinect;
std::string *message;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

/** @brief Initializes Kinect interaction
*   @param
*   @return
*
* Initializes Kinect interaction, calling the init()
* method of the interaction object.
*
*/
void init(){
    kinect = new KinectInteraction(),
    kinect->init();

}

/** @brief Function for server thread
*   @param
*   @return
*
* Runs the server function
*
*/
void *sendMsg(void*ptr){
  try{
    boost::asio::io_service io_service;
    Server server(io_service, message);
    io_service.run();
  }
  catch (std::exception& e){
    std::cerr << e.what() << std::endl;
  }
}

/** @brief Function for kinect thread
*   @param
*   @return
*
*
*
*/
void *graphics(void*ptr){

    bool die(false);
    int iter = 0;
    ofstream output;
    output.open ("output.xml");




   kinect->train();

    while (!die) {

        kinect->run();
        kinect->draw();

        if(iter % 10 ==0) kinect->detect();

        //Recordning commented, TODO: move to function
        /*if(iter == 100){
            std::cout << "recording..." << std::endl;
        }
        if(iter == 150){
            kinect->record(pro);
            FileStorage fs("new_prot1.yml", FileStorage::WRITE);
            if (!fs.isOpened()){
            fs.open("new_prot1.yml", FileStorage::WRITE);
            }
            std::cout << "done!" << std::endl;
            fs << "prot_come" << pro;
            fs.release();

        }*/



        pthread_mutex_lock(&mutex);
        *message = kinect->printPeople();
        output << *message << std::endl;

        pthread_mutex_unlock(&mutex);

        usleep(50000);

    	char k = cvWaitKey(5);
		if( k == 27 ){
			output.close();
			break;
		}
        iter++;
    }


    kinect->stop();
}

int main(int argc, char **argv){
    init();

    message = new std::string("bleh");
    pthread_t graphicsThread, serverThread;
    char *arg1 = "";
    char *arg2 = "";

    int  iret1, iret2;

    //Create threads
    iret1 = pthread_create( &graphicsThread, NULL, graphics, (void*) arg1);
    iret2 = pthread_create( &serverThread, NULL, sendMsg, (void*) arg2);

    //Join threads
    pthread_join( graphicsThread, NULL);
    pthread_join( serverThread, NULL);



    return 0;
}
